import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutterdemo/base/BasePage.dart';
import 'package:flutterdemo/base/liftcycle/liftcycle.dart';
import 'package:flutterdemo/smartform/utils/log.dart';

class NestedScrollPage extends StatefulWidget {
  @override
  NestedScrollState createState() {
    return NestedScrollState();
  }
}

class NestedScrollState extends AbsLiftCycleBaseState<NestedScrollPage> {
  ///滚动监听设置
  ScrollController? _scrollController;

  ///头部背景布局 true滚动一定的高度 false 滚动高度为0
  bool headerWhite = false;


  ///页面滚动头部处理
  List<Widget> _headerSliverBuilder(
      BuildContext context, bool innerBoxIsScrolled) {
    return <Widget>[buildSliverAppBar(context)];
  }

  List<Widget> buildHeader(BuildContext context, bool innerBoxIsScrolled) {
    return <Widget>[
      SliverOverlapAbsorber(
        handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context),
        sliver: Container(
          child: SliverPersistentHeader(
            pinned: true,
            floating: false,
            delegate: Delegate(
                title: buildTitle(),
                titleHeight: 60,
                expandedHeight: 300,
                flexibleSpace: Container(),
                bottom: Container(),
                bottomHeight: 200),
          ),
        )
      ),
    ];
  }

  ///导航部分渲染
  Widget buildSliverAppBar(BuildContext context) {
    return SliverAppBar(
      title: buildTitle(),
      // automaticallyImplyLeading: false,
      centerTitle: true,
      //当此值为true时 SliverAppBar 会固定在页面顶部
      //当此值为fase时 SliverAppBar 会随着滑动向上滑动
      pinned: true,
      //滚动是是否拉伸图片
      stretch: true,
      //展开区域的高度
      expandedHeight: 600,
      //当snap配置为true时，向下滑动页面，SliverAppBar（以及其中配置的flexibleSpace内容）会立即显示出来，
      //反之当snap配置为false时，向下滑动时，只有当ListView的数据滑动到顶部时，SliverAppBar才会下拉显示出来。
      snap: false,
      //阴影
      elevation: 0,
      //背景颜色
      backgroundColor: headerWhite ? Colors.white : Color(0xFFF4F5F7),
      //App bar 的亮度，有白色和黑色两种主题，默认值为 ThemeData.primaryColorBrightness
      //在标题左侧显示的一个控件，在首页通常显示应用的 logo；在其他界面通常显示为返回按钮
      leading: IconButton(
          icon: Image.asset(
            'assets/image/back.png',
            height: 22,
            width: 22,
          ),
          onPressed: () {
            //TODO: 返回事件处理
          }),
      //一个显示在 AppBar 下方的控件，高度和 AppBar 高度一样， // 可以实现一些特殊的效果，该属性通常在 SliverAppBar 中使用
      flexibleSpace: FlexibleSpaceBar(
        background: buildAppBarBackground(context),
        stretchModes: [StretchMode.fadeTitle],
        collapseMode: CollapseMode.none,
      ),
      bottom: AppBar(
        automaticallyImplyLeading: false,
        toolbarHeight: 20,
        title: Container(
          width: ScreenUtil().screenWidth,
          child: Text(
            "nihaolihuany",
            style: TextStyle(color: Colors.deepOrange),
          ),
        ),
      ),
    );
  }

  ///渲染背景部分布局
  Widget buildAppBarBackground(BuildContext context) {
    return Stack(
      children: <Widget>[
        Container(
          height: 400,
          width: ScreenUtil().screenWidth,
          decoration: BoxDecoration(
              image: DecorationImage(
                  image: NetworkImage(
                      'https://p0.meituan.net/movie/0e81560dc9910a6a658a82ec7a054ceb5075992.jpg@464w_644h_1e_1c'),
                  fit: BoxFit.fill)),
        ),
        Positioned(
            left: 0,
            right: 0,
            bottom: 0,
            child: Padding(
                padding: EdgeInsets.symmetric(horizontal: 15),
                child: (Container(
                  height: 160,
                  alignment: Alignment.centerLeft,
                  padding: EdgeInsets.all(15),
                  width: ScreenUtil().screenWidth,
                  decoration: new BoxDecoration(
                      color: Colors.white,
                      borderRadius: new BorderRadius.circular(8.0)),
                  child: (Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      Text('剧情简介',
                          style: TextStyle(
                              fontSize: 15,
                              fontWeight: FontWeight.w700,
                              fontFamily: 'PingFangSC-Semibold',
                              color: Color(0xff000000))),
                      Text(
                          '电影《长津湖》以抗美援朝战争第二次战役中的长津湖战役为背景，讲述了一段波澜壮阔的历史：71年前，中国人民志愿军赴朝作战，在极寒严酷环境下，东线作战部队凭着钢铁意志和英勇无畏的战斗精神一路追击，奋勇杀敌，扭转了战场态势，打出了军威国威')
                    ],
                  )),
                )))),
      ],
    );
  }

  Widget buildSliverBody(BuildContext context){
    return Container(
      height: 1000,
      width: 500,
      decoration: BoxDecoration(color: Colors.blue),
      child: Text("nihao"),
    );
    // return SafeArea(
    //   top: false,
    //   bottom: false,
    //   child: Column(
    //     children: <Widget>[
    //       Padding(
    //         ///设置卡片外间距padding
    //         padding: EdgeInsets.only(left: 15.0, top: 10.0, right: 15.0, bottom: 0),
    //         child: Container(
    //             padding: EdgeInsets.all(15.0),
    //             decoration: new BoxDecoration(
    //                 color: Colors.white,
    //                 borderRadius: new BorderRadius.circular(8.0)
    //             ),
    //             child: Text('印象中第一次一大家子一起来看电影，姥爷就是志愿军，他一辈子没进过电影院，开始还担心会不会不适应，'
    //                 '感谢影院工作人员的照顾，姥爷全程非常投入，我坐在旁边看到他偷偷抹了好几次眼泪，刚才我问电影咋样，一直念叨“好，好哇，'
    //                 '我们那时候就是那样的，就是那样的……” 忽然觉得历史长河与我竟如此之近，刚刚的三个小时我看到的是遥远的70年前、是教科书里的战争，'
    //                 '更是姥爷的19岁，是真真切切的、他的青春年代！')
    //         ),
    //       ),
    //       Padding(
    //         ///设置卡片外间距padding
    //         padding: EdgeInsets.only(left: 15.0, top: 10.0, right: 15.0, bottom: 0),
    //         child: Container(
    //             padding: EdgeInsets.all(15.0),
    //             decoration: new BoxDecoration(
    //                 color: Colors.white,
    //                 borderRadius: new BorderRadius.circular(8.0)
    //             ),
    //             child: Text('《长津湖》绝对可以称得上是一部伟大的战争史诗了！！拍出了抗美援朝这场立国之战最真实的样子！拍出了我们志愿军战士英勇无畏的英雄性！'
    //                 '可歌可泣！气势恢宏！ 可以说《长津湖》不仅是目前国内战争电影的天花板，也是迄今为止一部把人和人性拍的最好的战争电影——这是非常难能可贵的！ '
    //                 '电影可以说是集合了中国一群最优秀最具雄性荷尔蒙的男演员出演！全员演技在线！其中令人印象最深刻的是易烊千玺饰演的伍万里。'
    //                 '他把一个新兵从懵懂参军到初入战场的恐惧慌乱再到经历了战火的淬炼后面对敌人果敢无畏的成长线演绎地淋漓尽致！人物角色的层次感，立体感和信任感都无比强烈！'
    //                 '不禁感叹，后生可畏！演得太好了，不，应该说是太出彩了！')
    //         ),
    //       )
    //     ],
    //   ),
    // );
  }

  Widget buildTitle() {
    return Container(
      width: ScreenUtil().scaleWidth,
      child: Stack(
        alignment: Alignment.center,
        children: [
          // Positioned(child: Image.asset("assets/image/back.png"), left: 20,),
          Positioned(
              child: Text(
            "chiji",
            style: TextStyle(color: Colors.black87),
          ))
        ],
      ),
    );
  }

  @override
  void onCreate() {
    Log.logWsq("$runType onCreate");
    _scrollController = ScrollController();


  }

  @override
  Widget onBuildWidget(BuildContext context) {
    return ScreenUtilInit(
      designSize: Size(375, 812),
      builder: (context, child) => Scaffold(
        body: NestedScrollView(
          scrollBehavior: ScrollBehavior(),
          physics: NeverScrollableScrollPhysics(),
          headerSliverBuilder: buildHeader,
          body: buildSliverBody(context),
          controller: _scrollController,
        ),
      ),
    );
  }

  @override
  void onDestroy() {
    Log.logWsq("$runType onDestroy");
  }

  @override
  void onPause() {
    Log.logWsq("$runType onPause");
  }

  @override
  void onResume() {
    Log.logWsq("$runType onResume");
  }
}

class Delegate extends SliverPersistentHeaderDelegate {
  double _minExtent = 0;
  double _maxExtent = 0;

  double titleHeight;
  Widget title;
  double expandedHeight;
  Widget flexibleSpace;
  double bottomHeight;
  Widget bottom;

  Delegate(
      {required this.title,
      required this.titleHeight,
      required this.expandedHeight,
      required this.flexibleSpace,
      required this.bottom,
      required this.bottomHeight}) {
    _minExtent = titleHeight + bottomHeight;
    _maxExtent = expandedHeight + bottomHeight;
  }

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    _minExtent = titleHeight + bottomHeight;
    _maxExtent = expandedHeight + bottomHeight;
    //创建child子组件
    //shrinkOffset：child偏移值minExtent~maxExtent
    //overlapsContent：SliverPersistentHeader覆盖其他子组件返回true，否则返回false
    // print('shrinkOffset = $shrinkOffset overlapsContent = $overlapsContent');
    double flexibleSpaceTop = -shrinkOffset;
    double bottomTop = expandedHeight - shrinkOffset;
    var width = MediaQuery.of(context).size.width;
    print("flexibleSpaceTop: $flexibleSpaceTop bottomTop:$bottomTop");

    return Container(
      height: expandedHeight + bottomHeight - shrinkOffset,
      decoration: BoxDecoration(
        color: Color(0x66aaaaaa),
      ),
      child: Stack(
        alignment: Alignment.center,
        children: [
          Positioned(
            child: Container(
              decoration: BoxDecoration(color: Color(0x440000ff)),
              height: expandedHeight,
              width: width,
              child: flexibleSpace ?? Container(),
            ),
            // height: expandedHeight,
            top: flexibleSpaceTop,
          ),
          Positioned(
            child: Container(
              decoration: BoxDecoration(color: Color(0x4400ff00)),
              height: titleHeight,
              width: width,
              child: title ?? Container(),
            ),
            height: titleHeight,
            width: width,
            top: 0,
          ),
          Positioned(
            child: Container(
              decoration: BoxDecoration(color: Color(0x44ff0000)),
              height: bottomHeight,
              width: width,
              child: bottom ?? Container(),
            ),
            top: bottomTop,
            height: bottomHeight,
          ),
        ],
      ),
    );
  }

  @override
  double get maxExtent => _maxExtent;

  @override
  double get minExtent => _minExtent;

  @override
  bool shouldRebuild(covariant SliverPersistentHeaderDelegate oldDelegate) {
    return this != oldDelegate;
  }
}
